%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%copyright (c) 2012  Matthew Caudill
%
%this program is free software: you can redistribute it and/or modify
%it under the terms of the gnu general public license as published by
%the free software foundation, either version 3 of the license, or
%at your option) any later version.

%this program is distributed in the hope that it will be useful,
%but without any warranty; without even the implied warranty of
%merchantability or fitness for a particular purpose.  see the
%gnu general public license for more details.

%you should have received a copy of the gnu general public license
%along with this program.  if not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [imageFileNames, missingStacks, imagePath] = ...
                                            stimImageMatcher(stimFileNames)
                                        
% STIMIMAGEMATCHER takes in a cell array of stimulus fileNames and returns
% back a cell array image file names. This is accomplished by extracting
% the date info from the stimulus file name, moving to that directory
% within the images directory and lovating tiff images with a cell number
% matching that of the stimulus file name.
%INPUTS:            stimFileNames, a cell array of stimulus trial sets
%OUTPUTS:           imageFileNames, a cell array of image file stacks

%%%%%%%%%%%%%%%%%%%%%%%%%%% TESTING FILENAMES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% stimFileNames=...
%      {'MSC_2012-11-27_n1orientation_1_Trials',...
%       'MSC_2012-11-27_n1orientation_2_Trials',...
%       'MSC_2012-11-27_n1orientation_3_Trials'};

% We are looking for tiff images with the following names (in practice dir)
% n1orientation_1_001
% n1orientation_1_002
% n1orientation_2_001
% n1orientation_2_002
% so the method to locate the image files corresponding to one stimulus
% file will be to open the folder (org by dates) and search for the exp id
% (e.g. n1orientation and then get the image files with a matching stimulus
% set number (i.e. _1_ or _2_)

%%%%%%%%%%%%%%%% LOCATE DIRECTORY WHERE IMAGE FILES ARE STORED %%%%%%%%%%%%
ImExpDirInformation;
% We start our search in the image directory
baseImageDir = dirInfo.imageFileLoc;
%test dir
%baseImageDir = 'E:\Scanziani_Lab\missedTriggsTest\images\';

% Get the directory structure array of the base image directory
imageFolders = dir(baseImageDir);
% List all folder names in the base image directory
folderNames = {imageFolders(:).name};

% There are two errors that can occur when matching the stimulus files to
% their respective image stacks. 1. The folder containing the image files
% matching the date in the stimulus file Name is missing. 2. a tiff stack
% within that folder corresponding to a specific trial in the stimulus set
% is missing. We initialize cell array to capture these potentially missing
% folders and files
% initialize missing Image folder cell array.
missingFolders = {};
% initialize missing image files
missingStacks = {};

imageFileNames = {};

%##########################################################################
% Note to me: This program can be made a little better. It allows for the
% possibility that stim files may have image files in separate folders.
% This is probably not true. Likely the user will select stim files
% corresponding to a single neuron on 1 single day so it is unnecessary to
% repeatedly get a new folder name for the images for each stim file. I
% will correct this later
%##########################################################################

% get the date the stimulus was presented from the stimulus fileName
% (autogenerated by stimulus generation program)
for fileName = 1:numel(stimFileNames)
    stimFileName = stimFileNames{fileName};
    underscores = strfind(stimFileName,'_');
    % get date ( is between first two underscores)
    date = stimFileName(underscores(1)+1:underscores(2)-1);
    % Check that date contains zeros before single digits
    formatIn = 'yyyy-mm-dd';
    dateNumber = datenum(date,formatIn);
    formatOut = 'mm-dd-yyyy';
    date = datestr(dateNumber,formatOut);
    
    % remove hypens
    date = strrep(date,'-','');
    
    % pass back out a single folder where the images are kept so other programs
    % like tiffLoader can load those files (see programmer note above. We
    % are repeating the fullfile operation unnecessarily here. Will correct
    % later
    imagePath = fullfile(baseImageDir,date);
    
    if any(strcmp(date, folderNames))
        %if the date matches one of the folder names, get all the files in
        % that folder
        fileStruct = dir(fullfile(baseImageDir,date));
        files = {fileStruct.name};
        % get the filenames of the images that match our cell name and exp
        % type (i.e. n1orientation)
        cellNameExp = stimFileName(underscores(2)+1:underscores(3)-1);
        % get the stimulus set number
        stimSetNum = stimFileName(underscores(end-1):underscores(end));
        %
        % Construct the image substring token name we are looking for (e.g.
        % n1orientation_1_) from the cellNameExp and the stimSetNum
        imageToken = [cellNameExp,stimSetNum];
        %
        % Now we must compare this image token to the actual image file
        % names 
        for imageFile = 1:numel(files)
            if strfind(files{imageFile},imageToken)
                imageFileNames = [imageFileNames, files(imageFile)];    
            end
        end
        
        if ~any(cell2mat(strfind(files, imageToken)))
                missingStacks = [missingStacks, imageToken];
                missingStacks=[ '**COULD NOT LOCATE IMAGE FILES FOR**',...
                                missingStacks,...
                                'Remove stimulus file before proceeding'];
                errordlg(missingStacks,'ExpMaker Could Not Find:')
        end
    else
        missingFolders = [missingFolders, date];
    end
end


